<template>
  <div>
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <el-form-item label="标签名称" prop="tagId">
            <template v-if="drawerType === 'add'">
              <el-select v-model="editForm.tagId" filterable remote :remote-method="getTagNm" @change="changeTag">
                <el-option
                  v-for="item in tagList"
                  :key="item.tagId"
                  :label="item.tagNm"
                  :value="item.tagId"
                ></el-option>
              </el-select>
            </template>
            <el-input v-model="editForm.tagNm" disabled v-else></el-input>
          </el-form-item>
          <el-form-item label="取值类型" prop="valueType">
            <el-select v-model="editForm.valueType" disabled>
              <el-option label="---" value=""></el-option>
              <el-option
                v-for="item in $dictList('value_type')"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="editForm.enumTag">
            <tag-content-header search refresh @toolFun="toolFun">
              <template #title>
                <span>枚举值列表</span>
              </template>
            </tag-content-header>
            <tag-table
              ref="table"
              @refresh="getList"
              :data="dataList"
              :loading="loading"
              :columns="columns"
              :params="params"
              :total="totalSize"
              selection
              rowKey="cdVal"
            >
            </tag-table>
          </template>
          <template v-else>
            <template v-if="editForm.valueType == 3">
              <tag-content-header>
                <template #title>
                  <span>标识列表</span>
                </template>
              </tag-content-header>
              <tag-table
                ref="idnttable"
                :data="idntdataList"
                :columns="columns"
                selection
                rowKey="cdVal"
                :pagination="false"
              >
              </tag-table>
            </template>
            <el-form-item prop="labGrps" label="分组规则" v-else>
              <config-range :target="editForm" @addRule="addRule" @removeRule="removeRule"></config-range>
            </el-form-item>
          </template>
          <el-form-item label="填写默认值" prop="isDefaultValue">
            <!-- <el-input v-model="editForm.defaultValue" placeholder="请输入标签默认值,如不填则为空"></el-input> -->
            <el-radio-group v-model="editForm.isDefaultValue">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="editForm.isDefaultValue">
            <el-row :gutter="20" class="default-content">
              <el-col :span="10">
                <el-form-item
                  prop="tagDefaultValue"
                  :label="editForm.enumTag ? '枚举值' : '代码值'"
                  label-width="190px"
                >
                  <el-input v-model="editForm.tagDefaultValue"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item prop="description" label="描述" label-width="60px">
                  <el-input v-model="editForm.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="$emit('clearDrawer')">关闭</el-button>
      <el-button type="primary" @click="submit">下一步</el-button>
    </div>
  </div>
</template>

<script>
import configRange from './config-range'
export default {
  props: {
    drawerType: {
      type: String,
      default: 'add'
    }
  },
  components: {
    configRange
  },
  data() {
    return {
      tagList: [],
      loading: false,
      dataList: [],
      columns: [
        {
          show: true,
          label: '枚举值',
          prop: 'cdVal',
          search: true,
          searchKey: '',
          align: 'center'
        },
        {
          show: true,
          label: '枚举值描述',
          prop: 'cdDesc',
          search: true,
          searchKey: '',
          align: 'center'
        }
      ],
      idntdataList: [
        {
          cdDesc: '是',
          cdVal: 1
        },
        {
          cdDesc: '否',
          cdVal: 0
        }
      ],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      selectedVal: [],
      editForm: {
        tagId: '',
        tagNm: '',
        isDefaultValue: 0,
        tagDefaultValue: '',
        description: '',
        enumTag: '',
        valueType: '',
        labGrps: [
          {
            codeCd: '',
            codeDesc: '',
            valLft: '',
            valRit: '',
            fluctuationThreshold: ''
          }
        ]
      },
      editFormRules: {
        tagId: [{ required: true, message: '标签名称不能为空', trigger: 'change' }],
        tagDefaultValue: [{ required: true, message: '默认值不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      tagDetail: {}
    }
  },
  methods: {
    init(params) {
      this.editForm.tagId = params.tagId
      if (this.editForm.tagId) this.getDetail()
      this.$nextTick(() => this.$refs.editForm.clearValidate())
    },
    getTagNm(query) {
      if (!query) {
        this.tagList = []
        return
      }
      this.$ajax({
        url: this.$ajax.setUrl(`tag/tagDataBox/getTagList/${query}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tagList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    changeTag(tagId) {
      const tag = this.tagList.find(item => item.tagId === tagId)
      if (tag) {
        this.editForm.tagNm = tag.tagNm
        this.editForm.enumTag = tag.enumTag
        this.editForm.valueType = tag.valueType
        this.getList()
      }
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`tag/tagDataBox/getTagBoxConfigInfo/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          const configJson = JSON.parse(data.data.tagConfigJson)
          this.editForm.tagNm = data.data.tagNm
          this.editForm.isDefaultValue = data.data.isDefaultValue
          this.editForm.valueType = data.data.tagType
          if (configJson.codeType === 'enum') {
            this.editForm.enumTag = 1
            this.selectedVal = configJson.codeConfig
            this.getList()
          } else {
            this.editForm.enumTag = 0
            if (data.data.tagType == 3) {
              this.selectedVal = configJson.codeConfig
            } else {
              this.editForm.labGrps = configJson.codeConfig
            }
          }
          if (this.editForm.isDefaultValue) {
            this.editForm.tagDefaultValue = configJson.defaultValue.tagDefaultValue
            this.editForm.description = configJson.defaultValue.description
          }
          this.getTagNm(this.editForm.tagNm)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getList() {
      this.loading = true
      this.params.queryParams.tagId = this.editForm.tagId
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagEnumVal/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dataList = data.data.records
          this.totalSize = data.data.totalSize
          this.selectedVal.forEach(v =>
            this.$nextTick(() => {
              let row = this.dataList.find(item => item.cdVal === v.codeCd)
              if (row) {
                let selectedRow = this.$refs.table.getSelectList()
                if (!selectedRow.find(item => item.cdVal === row.cdVal))
                  this.$refs.table.$refs.tagTable.toggleRowSelection(row)
              }
            })
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    addRule(index) {
      this.editForm.labGrps.splice(index, 0, {
        codeCd: '',
        codeDesc: '',
        valLft: index >= 0 ? this.editForm.labGrps[index - 1].valRit : '',
        valRit: '',
        fluctuationThreshold: ''
      })
      this.$forceUpdate()
    },
    removeRule(index) {
      this.editForm.labGrps.splice(index, 1)
      this.$forceUpdate()
    },
    submit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let cdConfig = {
            codeType: 'other',
            codeConfig: this.editForm.labGrps
          }
          if (this.editForm.enumTag) {
            const eunmList = this.$refs.table.getSelectList()
            if (!eunmList.length) {
              this.$message.info('请选择枚举值！')
              return
            }
            cdConfig.codeType = 'enum'
            cdConfig.codeConfig = []
            eunmList.forEach(item =>
              cdConfig.codeConfig.push({ codeCd: item.cdVal, codeDesc: item.cdDesc, fluctuationThreshold: '' })
            )
          } else {
            if (this.editForm.valueType == 3) {
              const selectList = this.$refs.idnttable.getSelectList()
              if (!selectList.length) {
                this.$message.info('请选择枚举值！')
                return
              }
              cdConfig.codeType = 'enum'
              cdConfig.codeConfig = []
              selectList.forEach(item =>
                cdConfig.codeConfig.push({ codeCd: item.cdVal, codeDesc: item.cdDesc, fluctuationThreshold: '' })
              )
            }
          }
          if (this.editForm.isDefaultValue) {
            cdConfig.defaultValue = {
              tagDefaultValue: this.editForm.tagDefaultValue,
              description: this.editForm.description
            }
          }
          let params = {
            tagId: this.editForm.tagId,
            tagNm: this.editForm.tagNm,
            tagType: this.editForm.valueType,
            enumTag: this.editForm.enumTag,
            isDefaultValue: this.editForm.isDefaultValue
          }
          params.tagConfigJson = cdConfig
          this.$emit('next', params)
        }
      })
    },
    clearDrawer() {
      this.editForm.tagId = ''
      this.editForm.tagNm = ''
      this.editForm.isDefaultValue = 0
      this.editForm.enumTag = ''
      this.editForm.valueType = ''
      this.editForm.labGrps = [
        {
          codeCd: '',
          codeDesc: '',
          valLft: '',
          valRit: '',
          fluctuationThreshold: ''
        }
      ]
      this.dataList = []
      this.tagList = []
      this.selectedVal = []
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
    }
  }
}
</script>

<style lang="scss"></style>
